package com.hgx.file.server.rest;

import com.hgx.common.exception.CommonException;
import com.hgx.common.rest.response.CommonResponse;
import com.hgx.file.server.client.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Description:文件上传下载
 * Author: hanguixian
 * CreateDate: 2019/08/23 10:08
 * Modified by:
 */
@RestController
@RequestMapping("file")
@Api(tags = "文件Controller")
@Slf4j
public class FileController {

    @Autowired
    private FastDFSClient dfsClient;


    @PostMapping("/upload")
    @ApiOperation(value = "通用文件上传")
    public CommonResponse<String> uploadFile(MultipartFile file) {
        log.info("上传文件开始,文件名:{}", file.getOriginalFilename());
        String url;
        try {
            url = dfsClient.uploadFile(file);
        } catch (IOException e) {
            log.info("上传文件失败,文件名:{}", file.getOriginalFilename());
            throw new CommonException("上传文件错误");
        }
        log.info("上传文件成功,文件路径:{}", url);
        return CommonResponse.ok(url);
    }

    @RequestMapping("/download")
    @ApiOperation(value = "通用文件下载")
    public ResponseEntity<byte[]> download(String fileUrl, HttpServletResponse response) {
        log.info("下载文件开始,路径:{}", fileUrl);
        if (StringUtils.isBlank(fileUrl)) {
            throw new CommonException("文件路径不能为null");
        }
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

        try {
            OutputStream os = response.getOutputStream();
            byte[] b = dfsClient.download(fileUrl);
            os.write(b, 0, b.length);
            os.close();
            log.info("下载文件成功,路径:{}", fileUrl);
        } catch (Exception e) {
            log.info("下载文件失败,路径:{}", fileUrl);
            throw new CommonException("文件下载失败");
        }
        return null;
    }

}
